package com.tang.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.tang.config.enums.OrderStatus;
import com.tang.mapper.TProductMapper;
import com.tang.pojo.TOrderInfo;
import com.tang.mapper.TOrderInfoMapper;
import com.tang.pojo.TProduct;
import com.tang.service.TOrderInfoService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.tang.util.OrderNoUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.time.Duration;
import java.time.Instant;
import java.util.List;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author tang
 * @since 2025-03-27
 */
@Service
@Slf4j
public class TOrderInfoServiceImpl extends ServiceImpl<TOrderInfoMapper, TOrderInfo> implements TOrderInfoService {
    @Resource
    private TProductMapper productMapper;

    @Override
    public TOrderInfo createOrderByProductId(Long productId) {
//查找已存在但未支付的订单
        TOrderInfo orderInfo = this.getNoPayOrderByProductId(productId);
        if( orderInfo != null){
            return orderInfo;
        }
//获取商品信息
        TProduct product = productMapper.selectById(productId);
//生成订单
        orderInfo = new TOrderInfo();
        orderInfo.setTitle(product.getTitle());
        orderInfo.setOrderNo(OrderNoUtils.getOrderNo()); //订单号
        orderInfo.setProductId(productId);
        orderInfo.setTotalFee(product.getPrice()); //分
        orderInfo.setOrderStatus(OrderStatus.NOTPAY.getType());
        baseMapper.insert(orderInfo);
        return orderInfo;
    }

    /**
     * 根据商品id查询未支付订单
     * 防止重复创建订单对象
     * @param productId
     * @return
     */
    private TOrderInfo getNoPayOrderByProductId(Long productId) {
        QueryWrapper<TOrderInfo> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("product_id", productId);
        queryWrapper.eq("order_status", OrderStatus.NOTPAY.getType());
// queryWrapper.eq("user_id", userId);
        TOrderInfo orderInfo = baseMapper.selectOne(queryWrapper);
        return orderInfo;
    }

    /**
     * 存储订单二维码
     * @param orderNo
     * @param codeUrl
     */
    @Override
    public void saveCodeUrl(String orderNo, String codeUrl) {
        QueryWrapper<TOrderInfo> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("order_no", orderNo);
        TOrderInfo orderInfo = new TOrderInfo();
        orderInfo.setCodeUrl(codeUrl);
        baseMapper.update(orderInfo, queryWrapper);
    }

    /**
     * 查询订单列表，并倒序查询
     * @return
     */
    @Override
    public List<TOrderInfo> listOrderByCreateTimeDesc() {
        QueryWrapper<TOrderInfo> queryWrapper = new QueryWrapper<TOrderInfo>
                ().orderByDesc("create_time");
        return baseMapper.selectList(queryWrapper);
    }


    /**
     * 根据订单编号更新订单状态
     * @param orderNo
     * @param orderStatus
    （3）处理支付日志
    PaymentInfoService
    接口：
    实现：
     */
    public void updateStatusByOrderNo(String orderNo, OrderStatus orderStatus) {
        log.info("更新订单状态 ===> {}", orderStatus.getType());
        QueryWrapper<TOrderInfo> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("order_no", orderNo);
        TOrderInfo orderInfo = new TOrderInfo();
        orderInfo.setOrderStatus(orderStatus.getType());
        baseMapper.update(orderInfo, queryWrapper);
    }


    /**
     * 根据订单号获取订单状态
     * @param orderNo
     * @return
     */
    @Override
    public String getOrderStatus(String orderNo) {
        QueryWrapper<TOrderInfo> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("order_no", orderNo);
        TOrderInfo orderInfo = baseMapper.selectOne(queryWrapper);
//防止被删除的订单的回调通知的调用
        if(orderInfo == null){
            return null;
        }
        return orderInfo.getOrderStatus();
    }

    /**
     * 找出创建超过minutes分钟并且未支付的订单
     * @param minutes
     * @return
     */
    @Override
    public List<TOrderInfo> getNoPayOrderByDuration(int minutes) {
//minutes分钟之前的时间
        Instant instant = Instant.now().minus(Duration.ofMinutes(minutes));
        QueryWrapper<TOrderInfo> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("order_status", OrderStatus.NOTPAY.getType());
        queryWrapper.le("create_time", instant);
        List<TOrderInfo> orderInfoList = baseMapper.selectList(queryWrapper);
        return orderInfoList;
    }

    /**
     * 根据订单号获取订单
     * @param orderNo
     * @return
     */
    @Override
    public TOrderInfo getOrderByOrderNo(String orderNo) {
        QueryWrapper<TOrderInfo> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("order_no", orderNo);
        TOrderInfo orderInfo = baseMapper.selectOne(queryWrapper);
        return orderInfo;
    }

}

